/***
 * @description: 设拿货模板弹框
 * @author:fj
 */
import React, { useState, useEffect } from 'react';
import CommonModal from '@/components/CommonModal';
import { Form, message, Select, Tooltip } from 'antd';
import CommonLoading from '@/components/CommonLoading';
import { setTakeTemplate, queryTakeGoodsPrintTemplate } from '../../service';
import { isEmpty } from 'lodash';

const { Option } = Select;

const TakeGoodsTemplateModal = ({ visible, ids, handleOk, handleCancel }) => {
  const [form] = Form.useForm();

  const [loading, setLoading] = useState(false);

  //拿货模板列表
  const [templateList, setTemplateList] = useState([]);

  //查询用户拿货模板
  const getTemplateList = async () => {
    setLoading(true);
    const { data, success } = await queryTakeGoodsPrintTemplate();
    if (success) {
      setTemplateList(data);
    }
    setLoading(false);
  };

  useEffect(() => {
    if (visible) {
      form.resetFields();
      getTemplateList();
    }
  }, [visible]);

  const onOk = () => {
    form
      .validateFields()
      .then((val) => {
        updateTemplateList(val);
      })
      .catch((err) => {
        console.log(err, 'err');
      });
  };

  const updateTemplateList = async (val) => {
    setLoading(true);
    const { success } = await setTakeTemplate({
      ...val,
      ids: ids,
      type: 0,
    });
    if (success) {
      message.success('拿货模板设置成功');
      handleOk();
    }
    setLoading(false);
  };

  //拿货模板下拉
  const templateListOptions =
    !isEmpty(templateList) &&
    templateList.map((item) => (
      <Option label={`${item.templateName}）`} key={item.id} value={item.id}>
        <Tooltip title={`${item.templateName}`}>{item.templateName}</Tooltip>
      </Option>
    ));

  return (
    <>
      <CommonModal
        title="设拿货模板"
        visible={visible}
        onCancel={handleCancel}
        onOk={onOk}
        maxHeight="200px"
        minHeight="100px"
        width={460}
      >
        <div className="form_box">
          <Form name="edit-certificate" form={form}>
            <Form.Item
              label="选择拿货模板"
              name="cofcTemplateId"
              rules={[{ required: true, message: '请选择拿货模板！' }]}
            >
              <Select
                showSearch
                optionFilterProp="label"
                size="small"
                placeholder="全部"
                style={{ width: 260 }}
              >
                {templateListOptions}
              </Select>
            </Form.Item>
          </Form>
        </div>
      </CommonModal>
      <CommonLoading loading={loading} />
    </>
  );
};

export default TakeGoodsTemplateModal;
